/**
 * @author harry
 * @date 2021/12/5/11:32
 */

package com.ui.group;

import com.controller.GroupController;
import com.ui.builder.ButtonBuilder;
import com.ui.builder.LabelBuilder;
import com.ui.builder.TextFieldBuilder;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AddGroup extends JFrame implements ActionListener {
    private final JPanel inputPanel = new JPanel();
    private final JPanel buttonPanel = new JPanel();
    private final JLabel valueLabel = LabelBuilder.makeLabel("分组名");
    private final JTextField valueInput = TextFieldBuilder.makeTextField(15);
    private final JButton submit = ButtonBuilder.makeButton("确认");
    private final JButton reset = ButtonBuilder.makeButton("重置");
    private final GroupController groupController = new GroupController();

    public AddGroup() {
        super("添加分组");

        //button listener
        submit.addActionListener(this);
        reset.addActionListener(this);

        //inputPanel
        inputPanel.setLayout(new GridLayout(2, 2, 0, 0));
        inputPanel.add(valueLabel);
        inputPanel.add(valueInput);
        inputPanel.add(new JLabel());
        inputPanel.add(new JLabel());

        //button add to panel
        buttonPanel.setLayout(new GridLayout(1, 2, 30, 0));
        buttonPanel.add(submit);
        buttonPanel.add(reset);

        //frame
        this.setLayout(new FlowLayout());
        this.setSize(400, 150);
        this.setLocationRelativeTo(null);
        this.add(inputPanel);
        this.add(buttonPanel);
        this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        if(source == submit) {
            String newGroup = valueInput.getText();
            if(newGroup.equals("")) {
                JOptionPane.showMessageDialog(null, "分组名不能为空");
            }
            else {
                boolean result = groupController.addGroup(newGroup);
                if (result) {
                    JOptionPane.showMessageDialog(null, "添加成功");
                } else {
                    JOptionPane.showMessageDialog(null, "添加失败");
                }
                this.setVisible(false);
            }
        }
        else if(source == reset) {
            valueInput.setText("");
        }
    }
}
